from flask import render_template, g, current_app, abort, request, jsonify

from info import constants
from info.models import Category, News
from info.utils.common import user_getter
from info.utils.response_code import RET
from . import index_blue


@index_blue.route('/news_list')
def news_list():
    # 与ajax关联, cid分类ID
    cid = request.args.get("cid", 1)
    page = request.args.get("page", 1)
    # per_page = request.args("per_page", 10)

    if not all([page, cid]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")
    try:
        page = int(page)
        cid = int(cid)
        # per_page =int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    filters = []
    filters.append(News.status == 0)
    if cid != 1:
        filters.append(News.category_id == cid)

    news_list, current_page, total_page = [], 1, 1
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,
                                                                                          constants.HOME_PAGE_MAX_NEWS,
                                                                                          False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    current_page = paginate.page
    total_page = paginate.pages
    news_model = paginate.items
    for new in news_model:
        news_list.append(new.to_basic_dict())

    data = {
        "news_list": news_list,
        'current_page': current_page,
        "total_page": total_page
    }
    return jsonify(errno=RET.OK, errmsg="查询成功", data=data)


@index_blue.route('/')
@user_getter
def index():
    # data需要传输的内容: user, click_news_list, categories
    user = g.user
    users = user.to_dict() if user else None
    # 查找分类
    categories_list = []
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return abort(500)

    for category in categories:
        categories_list.append(category.to_dict())

    click_news_list = []
    # 查找news排行
    try:
        news = News.query.order_by(News.clicks.desc()).paginate(1, constants.CLICK_RANK_MAX_NEWS, False)
    except Exception as e:
        current_app.logger.error(e)
        return abort(500)

    for new in news.items:
        click_news_list.append(new.to_basic_dict())

    data = {
        "user": users,
        "click_news_list": click_news_list,
        "categories_list": categories_list
    }
    return render_template("news/index.html", data=data)


@index_blue.route('/favicon.ico')
def favicon():
    return current_app.send_static_file("news/favicon.ico")
